package pw.hais.main.main_app.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.avos.avoscloud.im.v2.AVIMMessageHandler;
import com.avos.avoscloud.im.v2.AVIMMessageManager;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationMemberCountCallback;
import com.avos.avoscloud.im.v2.callback.AVIMMessagesQueryCallback;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pw.hais.main.R;
import pw.hais.main.main_app.adapter.ChatRoomMessageAdapter;
import pw.hais.main.main_app.app.BaseActivity;
import pw.hais.utils.EmptyUtil;
import pw.hais.utils.L;

/**
 * Created by Hais1992 on 2015/12/14.
 */
public class ChatRoomActivity extends BaseActivity implements View.OnClickListener {
    private EditText edit_send_text;
    private ImageButton btn_send;
    private ListView listview_chat;
    private AVIMConversation conversation;
    private Map<String,Object> user_attr;

    private ChatRoomMessageAdapter chatRoomMessageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatroom);

        listview_chat = (ListView) findViewById(R.id.listview_chat);
        edit_send_text = (EditText) findViewById(R.id.edit_send_text);
        btn_send = (ImageButton) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);

        if(app.user.userPhoto!=null){
            user_attr = new HashMap<>();
            user_attr.put("userPhoto", app.user.userPhoto.url);
        }

        //初始化接收
        AVIMMessageManager.registerDefaultMessageHandler(new CharMessageHandler());
        //登陆账号
        loadDialogShow("登录聊天室...");
        AVIMClient.getInstance(app.user.username).open(new AVIMClientCallback() {
            @Override
            public void done(AVIMClient avimClient, AVIMException e) {
                if (e == null) {
                    conversation = avimClient.getConversation("566e7ea060b20de54639fc67");
                    addCharRoom();
                } else {
                    L.showShort("进入聊天室失败!" + e.toString());
                    finish();
                }
            }
        });
    }

    /**
     * 加入 聊天室
     */
    private void addCharRoom() {
        loadDialogShow("初始化聊天室...");
        conversation.join(new AVIMConversationCallback() {
            @Override
            public void done(AVIMException e) {
                if (null != e) {
                    L.showShort("加入聊天室失败!" + e.toString());
                    finish();
                } else {
                    restallRoomRen();
                    getCharRoomLog();
                }
            }
        });

    }

    private void restallRoomRen(){
        //查询在线人数
        if(conversation==null)return;
        conversation.getMemberCount(new AVIMConversationMemberCountCallback() {
            @Override
            public void done(Integer integer, AVIMException e) {
                if (null == e) {
                    getSupportActionBar().setTitle("聊天室(" + integer + "在线)");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send:
                if (conversation != null) {
                    sendMessage();//发送信息
                }else{
                    L.showShort("登陆失败！退出房间");
                    finish();
                }
                break;
        }
    }

    private void sendMessage() {
        final String str_message = edit_send_text.getText() == null ? "" : edit_send_text.getText().toString().trim();
        if(EmptyUtil.emptyOfString(str_message))return;

        loadDialogShow("信息发送中...");

        final AVIMTextMessage message = new AVIMTextMessage();
        message.setText(str_message+"");
        message.setFrom(app.user.username);
        message.setTimestamp(new Date().getTime());
        if(user_attr!=null)message.setAttrs(user_attr);
        conversation.sendMessage(message, new AVIMConversationCallback() {
            @Override
            public void done(AVIMException e) {
                loadDialogDismiss();
                if (e != null) {
                    L.showShort("消息发送失败！" + e.toString());
                }else{
                    chatRoomMessageAdapter.appendData(message);
                    edit_send_text.setText(null);
                    listview_chat.setSelection(chatRoomMessageAdapter.getCount() - 1);
                    restallRoomRen();
                }
            }
        });
    }


    public class CharMessageHandler extends AVIMMessageHandler {
        @Override
        public void onMessage(AVIMMessage message, AVIMConversation conversation, AVIMClient client) {
            super.onMessage(message, conversation, client);
            if (message instanceof AVIMTextMessage) {

                chatRoomMessageAdapter.appendData(message);
                L.i("收到信息：" + ((AVIMTextMessage) message).getText());
                listview_chat.setSelection(chatRoomMessageAdapter.getCount() - 1);
                restallRoomRen();
            }
        }
    }



    /** 聊天记录 */
    private void getCharRoomLog(){
        loadDialogShow("获取聊天室信息...");
        conversation.queryMessages(20,new AVIMMessagesQueryCallback() {
            @Override
            public void done(List<AVIMMessage> list, AVIMException e) {

                loadDialogDismiss();
                chatRoomMessageAdapter = new ChatRoomMessageAdapter(list, ChatRoomMessageAdapter.ViewHolder.class);
                listview_chat.setAdapter(chatRoomMessageAdapter);
                listview_chat.setSelection(chatRoomMessageAdapter.getCount()-1);
            }
        });
    }

    /** 创建房间 */
    private void createCharRoom() {
        //注册默认的消息处理逻辑
        AVIMClient avimClient = AVIMClient.getInstance(app.user.username);
        avimClient.open(new AVIMClientCallback() {
            @Override
            public void done(AVIMClient avimClient, AVIMException e) {
                if (e == null) {
                    //登录成功
                    //创建一个 名为 "HelloWorld" 的暂态对话
                    avimClient.createConversation(new ArrayList<String>(), "海天盛筵", null, true, new AVIMConversationCreatedCallback() {
                        @Override
                        public void done(AVIMConversation conv, AVIMException e) {
                            conversation = conv;
                        }
                    });
                }
            }
        });
    }
}
